<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>侦听属性--深度</title>
  </head>
  <body>
    <div id="app">
      <input type="text" v-model="firstName" /> +
      <input type="text" v-model="lastName" /> = {{fullName}}

      <button @click="start">开始监听</button>
      <button @click="stop">结束监听</button>
      {{count}}
      <button @click="count++">++</button>
    </div>
    <script src="../lib/vue.global.js"></script>

    <script>
      const app = Vue.createApp({
        data() {
          return {
            user: {
              firstName: "",
              lastName: "",
            },
            fullName: "",
            count: 1,
          };
        },

        //希望侦听到user的变化，而不是user下的属性变化
        watch: {
          user: {
            deep: true, //深度监听标识
            handler(newval) {
              //侦听的函数
              console.log(newval);
              this.fullName = newval.firstName + newval.lastName;
            },
            immediate: true, //开始就侦听一遍数据
          },
        },

        methods: {
          start() {
            this.unwatch = this.$watch("count", (newval) => {
              console.log(newval);
            });
          },
          stop() {
            this.unwatch();
          },
        },
      });
      app.mount("#app");
    </script>
  </body>
</html>
